package com.ruoyi.controller.traceability;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.traceability.MesTraceabilityRecord;
import com.ruoyi.domain.traceability.MesTraceabilityDetail;
import com.ruoyi.service.traceability.IMesTraceabilityRecordService;
import com.ruoyi.service.traceability.IMesTraceabilityDetailService;

/**
 * 追溯业务Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/mes/traceability")
public class MesTraceabilityController extends BaseController {
    @Autowired
    private IMesTraceabilityRecordService mesTraceabilityRecordService;
    
    @Autowired
    private IMesTraceabilityDetailService mesTraceabilityDetailService;

    /**
     * 正向追溯 - 根据原料批次追溯到成品
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @GetMapping("/forward/{batchCode}")
    public AjaxResult forwardTrace(@PathVariable String batchCode) {
        // 查询正向追溯记录
        List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByBatchCode(batchCode);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        
        // 获取追溯链详情
        if (!records.isEmpty()) {
            Long traceId = records.get(0).getTraceId();
            List<MesTraceabilityDetail> details = mesTraceabilityDetailService.selectDetailsByTraceId(traceId);
            result.put("details", details);
        }
        
        return success(result);
    }

    /**
     * 反向追溯 - 根据成品追溯到原料
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @GetMapping("/reverse/{productId}")
    public AjaxResult reverseTrace(@PathVariable Long productId) {
        // 查询反向追溯记录
        List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByProductId(productId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        
        // 获取追溯链详情
        if (!records.isEmpty()) {
            Long traceId = records.get(0).getTraceId();
            List<MesTraceabilityDetail> details = mesTraceabilityDetailService.selectDetailsByTraceId(traceId);
            result.put("details", details);
        }
        
        return success(result);
    }

    /**
     * 根据工单ID获取完整追溯信息
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @GetMapping("/workOrder/{workOrderId}")
    public AjaxResult getTraceByWorkOrder(@PathVariable Long workOrderId) {
        List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByWorkOrderId(workOrderId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        
        // 获取所有相关的追溯详情
        for (MesTraceabilityRecord record : records) {
            List<MesTraceabilityDetail> details = mesTraceabilityDetailService.selectDetailsByTraceId(record.getTraceId());
            result.put("details_" + record.getTraceId(), details);
        }
        
        return success(result);
    }

    /**
     * 追溯分析 - 获取追溯统计信息
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @GetMapping("/analysis")
    public AjaxResult getTraceAnalysis(@RequestParam(required = false) String traceType,
                                      @RequestParam(required = false) String startDate,
                                      @RequestParam(required = false) String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 根据类型查询追溯记录
        if (traceType != null && !traceType.isEmpty()) {
            List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByType(traceType);
            result.put("records", records);
            result.put("totalCount", records.size());
        }
        
        return success(result);
    }

    /**
     * 生成追溯报告
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @Log(title = "追溯报告", businessType = BusinessType.EXPORT)
    @PostMapping("/report")
    public AjaxResult generateReport(@RequestBody Map<String, Object> params) {
        // 根据参数生成追溯报告
        Map<String, Object> report = new HashMap<>();
        
        String traceType = (String) params.get("traceType");
        String objectId = (String) params.get("objectId");
        
        if ("batch".equals(traceType) && objectId != null) {
            List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByBatchCode(objectId);
            report.put("traceRecords", records);
        } else if ("product".equals(traceType) && objectId != null) {
            List<MesTraceabilityRecord> records = mesTraceabilityRecordService.selectTraceabilityByProductId(Long.valueOf(objectId));
            report.put("traceRecords", records);
        }
        
        report.put("reportTime", System.currentTimeMillis());
        report.put("reportType", traceType);
        
        return success(report);
    }

    /**
     * 获取追溯树结构数据
     */
    @PreAuthorize("@ss.hasPermi('mes:traceability:query')")
    @GetMapping("/tree/{traceId}")
    public AjaxResult getTraceTree(@PathVariable Long traceId) {
        // 获取追溯详情并构建树结构
        List<MesTraceabilityDetail> details = mesTraceabilityDetailService.selectDetailsByTraceId(traceId);
        
        // 这里可以实现树结构构建逻辑
        Map<String, Object> tree = new HashMap<>();
        tree.put("traceId", traceId);
        tree.put("nodes", details);
        
        return success(tree);
    }
}